<template>
  <div class="message-management">
    <div class="header">
      <h2>留言板管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索帖子标题或作者"
          style="width: 220px; margin-right: 16px;"
          clearable
        />
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-row :gutter="16">
        <el-col :span="3">
          <el-select
            v-model="filterForm.status"
            placeholder="帖子状态"
            clearable
            style="width: 100%"
          >
            <el-option label="待审核" value="pending" />
            <el-option label="已发布" value="published" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-col>
        <!-- <el-col :span="4">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-col> -->
        <el-col :span="3">
          <el-select
            v-model="filterForm.sortBy"
            placeholder="排序方式"
            style="width: 100%"
          >
            <el-option label="发布时间" value="createTime" />
            <el-option label="回复数量" value="replyCount" />
            <el-option label="点赞数量" value="likeCount" />
          </el-select>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
          <el-button @click="handleResetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button 
            type="success" 
            @click="handleBatchApprove"
            :disabled="selectedMessages.length === 0"
          >
            <el-icon><Check /></el-icon>
            批量通过
          </el-button>
          <el-button 
            type="warning" 
            @click="handleBatchReject"
            :disabled="selectedMessages.length === 0"
          >
            <el-icon><Close /></el-icon>
            批量拒绝
          </el-button>
          <el-button 
            type="danger" 
            @click="handleBatchDelete"
            :disabled="selectedMessages.length === 0"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>

    <div class="table-container">
      <el-table
        :data="filteredMessages"
        style="width: 100%"
        stripe
        border
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        
        <el-table-column prop="id" label="帖子ID" width="80" fixed="left" />
        
        <el-table-column prop="title" label="帖子标题" width="180" fixed="left">
          <template #default="scope">
            <div class="title-cell" >
              <el-button 
                type="text" 
                @click="handleViewDetail(scope.row)"
                class="title-link"
                :title="scope.row.title"
              >
                {{ scope.row.title.length > 15 ? scope.row.title.substring(0, 15) + '...' : scope.row.title }}
              </el-button>
              <el-tag v-if="scope.row.isTop" type="danger" size="small" class="top-tag">
                置顶
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="author" label="作者" width="120">
          <template #default="scope">
            <div class="author-cell">
              <el-avatar :size="30" :src="scope.row.authorAvatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="author-name">{{ scope.row.author }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="内容预览" width="200">
          <template #default="scope">
              <div class="content-preview">
                {{ scope.row.content.substring(0, 50) }}{{ scope.row.content.length > 50 ? '...' : '' }}
              </div>
          </template>
        </el-table-column>

        <el-table-column prop="replyCount" label="回复数" width="80" align="center">
          <!-- <template #default="scope">
            <el-badge :value="scope.row.replyCount" class="reply-badge" style="height: 40px; line-height: 40px;">
              <el-icon style="font-size: 20px;"><ChatDotRound /></el-icon>
            </el-badge>
          </template> -->
        </el-table-column>

        <el-table-column prop="likeCount" label="点赞数" width="80" align="center">
          <!-- <template #default="scope">
            <el-badge :value="scope.row.likeCount" class="like-badge">
              <el-icon><Star /></el-icon>
            </el-badge>
          </template> -->
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="发布时间" width="140">
          <template #default="scope">
            <span>{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(scope.row)"
                :icon="View"
              >
                查看
              </el-button>
              <el-button
                type="warning"
                size="small"
                @click="handleEdit(scope.row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-dropdown @command="(command) => handleAction(command, scope.row)">
                <el-button size="small" type="info">
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <!-- 已发布状态：只显示删除和置顶操作 -->
                    <template v-if="scope.row.status === 'published'">
                      <el-dropdown-item command="toggleTop">
                        <el-icon><Top /></el-icon>{{ scope.row.isTop ? '取消置顶' : '设为置顶' }}
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <el-icon><Delete /></el-icon>删除帖子
                      </el-dropdown-item>
                    </template>
                    
                    <!-- 待审核状态：只显示通过和拒绝操作 -->
                    <template v-else-if="scope.row.status === 'pending'">
                      <el-dropdown-item command="approve">
                        <el-icon><Check /></el-icon>通过审核
                      </el-dropdown-item>
                      <el-dropdown-item command="reject">
                        <el-icon><Close /></el-icon>拒绝审核
                      </el-dropdown-item>
                    </template>
                    
                    <!-- 已拒绝状态：只显示通过操作 -->
                    <template v-else-if="scope.row.status === 'rejected'">
                      <el-dropdown-item command="approve">
                        <el-icon><Check /></el-icon>通过审核
                      </el-dropdown-item>
                    </template>
                    
                    <!-- 其他状态：显示所有操作 -->
                    <template v-else>
                      <el-dropdown-item command="approve" v-if="scope.row.status !== 'published'">
                        <el-icon><Check /></el-icon>通过审核
                      </el-dropdown-item>
                      <el-dropdown-item command="reject" v-if="scope.row.status !== 'rejected'">
                        <el-icon><Close /></el-icon>拒绝审核
                      </el-dropdown-item>
                      <el-dropdown-item command="toggleTop">
                        <el-icon><Top /></el-icon>{{ scope.row.isTop ? '取消置顶' : '设为置顶' }}
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        <el-icon><Delete /></el-icon>删除帖子
                      </el-dropdown-item>
                    </template>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalMessages"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 帖子编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑帖子"
      width="800px"
      :top="'3%'"
      :close-on-click-modal="false"
    >
      <el-form
        v-if="editForm"
        :model="editForm"
        label-width="80px"
        :rules="editRules"
        ref="editFormRef"
      >
        <el-form-item label="帖子标题" prop="title">
          <el-input
            v-model="editForm.title"
            placeholder="请输入帖子标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="帖子内容" prop="content">
          <el-input
            v-model="editForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入帖子内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="帖子状态">
          <el-select v-model="editForm.status" style="width: 200px">
            <el-option label="待审核" value="pending" />
            <el-option label="已发布" value="published" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶设置">
          <el-switch
            v-model="editForm.isTop"
            active-text="置顶"
            inactive-text="普通"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit" :loading="editLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="帖子详情"
      width="900px"
      :top="'3%'"
      :close-on-click-modal="false"
    >
      <div v-if="currentMessage" class="message-detail">
        <div class="message-header">
          <h3>{{ currentMessage.title }}</h3>
          <div class="message-meta">
            <el-tag :type="getStatusTagType(currentMessage.status)" size="small">
              {{ getStatusText(currentMessage.status) }}
            </el-tag>
            <span class="author-info">
              <el-avatar :size="24" :src="currentMessage.authorAvatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              {{ currentMessage.author }}
            </span>
            <span class="time-info">{{ formatDate(currentMessage.createTime) }}</span>
          </div>
        </div>
        
        <div class="message-content">
          <p>{{ currentMessage.content }}</p>
          <div v-if="currentMessage.images && currentMessage.images.length > 0" class="message-images">
            <el-image
              v-for="(image, index) in currentMessage.images"
              :key="index"
              :src="image"
              :preview-src-list="currentMessage.images"
              fit="cover"
              style="width: 100px; height: 100px; margin-right: 8px; border-radius: 4px;"
            />
          </div>
        </div>

        <div class="message-stats">
          <el-statistic title="回复数" :value="currentMessage.replyCount" />
          <el-statistic title="点赞数" :value="currentMessage.likeCount" />
          <el-statistic title="浏览数" :value="currentMessage.viewCount" />
        </div>

        <!-- 回复列表 -->
        <div class="replies-section" v-if="currentReplies.length > 0">
          <div class="replies-header">
            <h4>回复列表 ({{ currentReplies.length }})</h4>
            <el-button 
              v-if="selectedReplies.length > 0"
              type="danger" 
              size="small"
              @click="handleBatchDeleteReplies"
            >
              删除选中回复
            </el-button>
          </div>
          
          <div class="replies-list">
            <div 
              v-for="reply in currentReplies" 
              :key="reply.id" 
              class="reply-item"
            >
              <el-checkbox 
                v-model="selectedReplies" 
                :label="reply.id"
                class="reply-checkbox"
              />
              <div class="reply-content">
                <div class="reply-header">
                  <el-avatar :size="24" :src="reply.authorAvatar">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <span class="reply-author">{{ reply.author }}</span>
                  <span class="reply-time">{{ formatDate(reply.createTime) }}</span>
                  <el-button 
                    type="danger" 
                    size="small" 
                    text
                    @click="handleDeleteReply(reply)"
                  >
                    删除
                  </el-button>
                </div>
                <div class="reply-text">{{ reply.content }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no-replies">
          <el-empty description="暂无回复" :image-size="80" />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button 
            v-if="currentMessage && currentMessage.status === 'pending'"
            type="success" 
            @click="handleApprove(currentMessage)"
          >
            通过审核
          </el-button>
          <el-button 
            v-if="currentMessage && currentMessage.status === 'pending'"
            type="warning" 
            @click="handleReject(currentMessage)"
          >
            拒绝审核
          </el-button>
          <el-button 
            type="info" 
            @click="handleEditFromDetail(currentMessage)"
          >
            编辑帖子
          </el-button>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核理由对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="审核理由"
      width="500px"
      :top="'3%'"
    >
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核动作">
          <el-tag :type="auditForm.action === 'approve' ? 'success' : 'warning'">
            {{ auditForm.action === 'approve' ? '通过审核' : '拒绝审核' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="审核理由">
          <el-input
            v-model="auditForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入审核理由（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAudit" :loading="auditLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Refresh, Search, Check, Close, Delete, View, User, 
  ChatDotRound, Star, Top, ArrowDown, Edit 
} from '@element-plus/icons-vue'




// 响应式数据
const loading = ref(false)
const auditLoading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalMessages = ref(0)
const detailDialogVisible = ref(false)
const auditDialogVisible = ref(false)
const currentMessage = ref(null)
const selectedMessages = ref([])
const selectedReplies = ref([])
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editForm = ref(null)
const editFormRef = ref(null)

// 筛选表单
const filterForm = reactive({
  status: '',
  dateRange: [],
  sortBy: 'createTime'
})

// 审核表单
const auditForm = reactive({
  action: '',
  reason: '',
  messageIds: []
})

// 编辑表单验证规则
const editRules = {
  title: [
    { required: true, message: '请输入帖子标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入帖子内容', trigger: 'blur' },
    { min: 1, max: 2000, message: '内容长度在 1 到 2000 个字符', trigger: 'blur' }
  ]
}

// 帖子数据
const messages = ref([
  {
    id: 1,
    title: '福州三坊七巷游记分享',
    author: '旅行达人小王',
    authorAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    content: '今天去了福州的三坊七巷，真的是太美了！古色古香的建筑，浓厚的历史文化氛围，让人流连忘返。特别推荐大家去看看严复故居和林觉民故居，了解一下福州的历史文化。',
    images: [
      'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      'https://cube.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
    ],
    status: 'published',
    replyCount: 15,
    likeCount: 32,
    viewCount: 156,
    isTop: true,
    createTime: '2024-03-20 14:30:00'
  },
  {
    id: 2,
    title: '鼓山登山攻略',
    author: '户外爱好者',
    authorAvatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    content: '分享一下鼓山登山的经验，建议早上7点开始爬山，避开人流高峰。山上的涌泉寺值得一看，还有千年古树。记得带足够的水和防晒用品。',
    images: [],
    status: 'pending',
    replyCount: 8,
    likeCount: 18,
    viewCount: 89,
    isTop: false,
    createTime: '2024-03-21 09:15:00'
  },
  {
    id: 3,
    title: '西湖公园春游记',
    author: '摄影师小李',
    authorAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    content: '春天的西湖公园真的很美，樱花盛开，湖水清澈。拍了很多照片，和大家分享一下。最佳拍摄时间是早上8-10点，光线最好。',
    images: [
      'https://cube.elemecdn.com/1/31/c5ad0c65cb2739df0e71ce4642a78jpeg.jpeg'
    ],
    status: 'published',
    replyCount: 23,
    likeCount: 45,
    viewCount: 234,
    isTop: false,
    createTime: '2024-03-19 16:20:00'
  },
  {
    id: 4,
    title: '马尾船政文化探索',
    author: '历史爱好者',
    authorAvatar: '',
    content: '马尾船政文化博物馆真的值得一去，了解了很多中国近代海军的历史。建议大家提前预约，周一闭馆要注意。',
    images: [],
    status: 'rejected',
    replyCount: 3,
    likeCount: 7,
    viewCount: 45,
    isTop: false,
    createTime: '2024-03-18 11:45:00'
  },
  {
    id: 5,
    title: '福州美食推荐',
    author: '美食博主',
    authorAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    content: '推荐几家福州的特色小吃店，鱼丸、肉燕、佛跳墙都很正宗。具体地址和营业时间我都整理好了，需要的朋友可以私信我。',
    images: [
      'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'
    ],
    status: 'pending',
    replyCount: 12,
    likeCount: 28,
    viewCount: 167,
    isTop: false,
    createTime: '2024-03-22 13:10:00'
  }
])

// 回复数据 - 所有回复数据
const allReplies = ref([
  {
    id: 1,
    messageId: 1,
    author: '游客A',
    authorAvatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    content: '写得很详细，谢谢分享！',
    createTime: '2024-03-20 15:30:00'
  },
  {
    id: 2,
    messageId: 1,
    author: '本地人',
    authorAvatar: '',
    content: '三坊七巷确实很不错，推荐晚上去，灯光很美。',
    createTime: '2024-03-20 16:45:00'
  },
  {
    id: 3,
    messageId: 1,
    author: '历史迷',
    authorAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    content: '严复故居真的值得一看，了解了很多历史知识。',
    createTime: '2024-03-20 18:20:00'
  }
])

// 当前帖子的回复列表
const currentReplies = computed(() => {
  if (!currentMessage.value) return []
  return allReplies.value.filter(reply => reply.messageId === currentMessage.value.id)
})

// 计算属性 - 过滤帖子
const filteredMessages = computed(() => {
  let result = messages.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(message => 
      message.title.toLowerCase().includes(query) ||
      message.author.toLowerCase().includes(query) ||
      message.content.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (filterForm.status) {
    result = result.filter(message => message.status === filterForm.status)
  }

  // 日期范围过滤
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    const [startDate, endDate] = filterForm.dateRange
    result = result.filter(message => {
      const messageDate = new Date(message.createTime).toISOString().split('T')[0]
      return messageDate >= startDate && messageDate <= endDate
    })
  }

  // 排序
  if (filterForm.sortBy) {
    result.sort((a, b) => {
      if (filterForm.sortBy === 'createTime') {
        return new Date(b.createTime) - new Date(a.createTime)
      } else if (filterForm.sortBy === 'replyCount') {
        return b.replyCount - a.replyCount
      } else if (filterForm.sortBy === 'likeCount') {
        return b.likeCount - a.likeCount
      }
      return 0
    })
  }

  return result
})

// 方法
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    published: '已发布',
    rejected: '已拒绝',
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    published: 'success',
    rejected: 'danger',
    deleted: 'info'
  }
  return typeMap[status] || 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const handleFilter = () => {
  currentPage.value = 1
  ElMessage.success('筛选完成')
}

const handleResetFilter = () => {
  filterForm.status = ''
  filterForm.dateRange = []
  filterForm.sortBy = 'createTime'
  searchQuery.value = ''
  currentPage.value = 1
  ElMessage.success('筛选条件已重置')
}

const handleRefresh = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据已刷新')
  }, 1000)
}

const handleSelectionChange = (selection) => {
  selectedMessages.value = selection.map(item => item.id)
}

const handleViewDetail = (message) => {
  currentMessage.value = message
  selectedReplies.value = []
  detailDialogVisible.value = true
}

const handleEdit = (message) => {
  editForm.value = {
    id: message.id,
    title: message.title,
    content: message.content,
    status: message.status,
    isTop: message.isTop
  }
  editDialogVisible.value = true
}

const handleEditFromDetail = (message) => {
  detailDialogVisible.value = false
  handleEdit(message)
}

const handleSaveEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    editLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新帖子数据
    const message = messages.value.find(m => m.id === editForm.value.id)
    if (message) {
      message.title = editForm.value.title
      message.content = editForm.value.content
      message.status = editForm.value.status
      message.isTop = editForm.value.isTop
    }
    
    ElMessage.success('帖子更新成功')
    editDialogVisible.value = false
    editForm.value = null
  } catch (error) {
    if (error !== false) { // 验证失败时不显示错误消息
      ElMessage.error('保存失败，请重试')
    }
  } finally {
    editLoading.value = false
  }
}

const handleStatusChange = async (message, newStatus) => {
  const oldStatus = message.status
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(`帖子状态已更新为：${getStatusText(newStatus)}`)
  } catch (error) {
    // 如果更新失败，恢复原状态
    message.status = oldStatus
    ElMessage.error('状态更新失败')
  }
}

const handleAction = (command, message) => {
  switch (command) {
    case 'approve':
      handleApprove(message)
      break
    case 'reject':
      handleReject(message)
      break
    case 'toggleTop':
      handleToggleTop(message)
      break
    case 'delete':
      handleDelete(message)
      break
  }
}

const handleApprove = (message) => {
  auditForm.action = 'approve'
  auditForm.messageIds = [message.id]
  auditForm.reason = ''
  auditDialogVisible.value = true
}

const handleReject = (message) => {
  auditForm.action = 'reject'
  auditForm.messageIds = [message.id]
  auditForm.reason = ''
  auditDialogVisible.value = true
}

const handleBatchApprove = () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请先选择要审核的帖子')
    return
  }
  auditForm.action = 'approve'
  auditForm.messageIds = [...selectedMessages.value]
  auditForm.reason = ''
  auditDialogVisible.value = true
}

const handleBatchReject = () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请先选择要审核的帖子')
    return
  }
  auditForm.action = 'reject'
  auditForm.messageIds = [...selectedMessages.value]
  auditForm.reason = ''
  auditDialogVisible.value = true
}

const confirmAudit = async () => {
  auditLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新帖子状态
    auditForm.messageIds.forEach(id => {
      const message = messages.value.find(m => m.id === id)
      if (message) {
        message.status = auditForm.action === 'approve' ? 'published' : 'rejected'
      }
    })
    
    const actionText = auditForm.action === 'approve' ? '通过' : '拒绝'
    ElMessage.success(`${auditForm.messageIds.length}个帖子已${actionText}审核`)
    
    auditDialogVisible.value = false
    selectedMessages.value = []
  } catch (error) {
    ElMessage.error('审核操作失败')
  } finally {
    auditLoading.value = false
  }
}

const handleToggleTop = async (message) => {
  try {
    await ElMessageBox.confirm(
      `确定要${message.isTop ? '取消置顶' : '设为置顶'}帖子 "${message.title}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    message.isTop = !message.isTop
    ElMessage.success(`帖子已${message.isTop ? '设为置顶' : '取消置顶'}`)
  } catch {
    ElMessage.info('已取消操作')
  }
}

const handleDelete = async (message) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除帖子 "${message.title}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const index = messages.value.findIndex(m => m.id === message.id)
    if (index > -1) {
      messages.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleBatchDelete = async () => {
  if (selectedMessages.value.length === 0) {
    ElMessage.warning('请先选择要删除的帖子')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedMessages.value.length} 个帖子吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    selectedMessages.value.forEach(id => {
      const index = messages.value.findIndex(m => m.id === id)
      if (index > -1) {
        messages.value.splice(index, 1)
      }
    })
    
    ElMessage.success(`成功删除 ${selectedMessages.value.length} 个帖子`)
    selectedMessages.value = []
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleDeleteReply = async (reply) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条回复吗？此操作不可恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const index = allReplies.value.findIndex(r => r.id === reply.id)
    if (index > -1) {
      allReplies.value.splice(index, 1)
      // 更新帖子回复数
      if (currentMessage.value) {
        currentMessage.value.replyCount--
        const message = messages.value.find(m => m.id === currentMessage.value.id)
        if (message) {
          message.replyCount--
        }
      }
      ElMessage.success('回复删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleBatchDeleteReplies = async () => {
  if (selectedReplies.value.length === 0) {
    ElMessage.warning('请先选择要删除的回复')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedReplies.value.length} 条回复吗？此操作不可恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    selectedReplies.value.forEach(replyId => {
      const index = allReplies.value.findIndex(r => r.id === replyId)
      if (index > -1) {
        allReplies.value.splice(index, 1)
      }
    })
    
    // 更新帖子回复数
    if (currentMessage.value) {
      currentMessage.value.replyCount -= selectedReplies.value.length
      const message = messages.value.find(m => m.id === currentMessage.value.id)
      if (message) {
        message.replyCount -= selectedReplies.value.length
      }
    }
    
    ElMessage.success(`成功删除 ${selectedReplies.value.length} 条回复`)
    selectedReplies.value = []
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 生命周期
onMounted(() => {
  totalMessages.value = messages.value.length
})
</script>

<style scoped>
.message-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.table-container {
  margin-bottom: 20px;
  overflow-x: auto;
}

.title-cell {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.title-link {
  font-weight: 500;
  color: #409eff;
  /* text-align: left; */
  padding: 0;
  /* max-width: 140px; */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.top-tag {
  flex-shrink: 0;
}

.author-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.author-name {
  font-size: 13px;
}

.content-preview {
  color: #606266;
  line-height: 1.4;
}

.reply-badge,
.like-badge {
  cursor: pointer;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 帖子详情样式 */
.message-detail {
  max-height: 550px;
  overflow-y: auto;
}

.message-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.message-header h3 {
  margin: 0 0 12px 0;
  color: #303133;
}

.message-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 14px;
  color: #909399;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 6px;
}

.message-content {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.message-content p {
  line-height: 1.6;
  color: #606266;
  margin: 0 0 12px 0;
}

.message-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.message-stats {
  display: flex;
  gap: 40px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.replies-section {
  margin-top: 20px;
}

.replies-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.replies-header h4 {
  margin: 0;
  color: #303133;
}

.replies-list {
  max-height: 300px;
  overflow-y: auto;
}

.reply-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 8px;
}

.reply-checkbox {
  margin-top: 4px;
}

.reply-content {
  flex: 1;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 13px;
}

.reply-author {
  font-weight: 500;
  color: #409eff;
}

.reply-time {
  color: #909399;
  margin-left: auto;
}

.reply-text {
  color: #606266;
  line-height: 1.4;
}

.no-replies {
  text-align: center;
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: space-between;
    margin-left: 0;
  }
  
  .filter-section .el-col {
    margin-bottom: 10px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .message-stats {
    flex-direction: column;
    gap: 16px;
  }
  
  .reply-item {
    flex-direction: column;
    gap: 8px;
  }
}

/* 表格滚动条样式 */
.table-container::-webkit-scrollbar,
.message-detail::-webkit-scrollbar,
.replies-list::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-container::-webkit-scrollbar-track,
.message-detail::-webkit-scrollbar-track,
.replies-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb,
.message-detail::-webkit-scrollbar-thumb,
.replies-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb:hover,
.message-detail::-webkit-scrollbar-thumb:hover,
.replies-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>